var Bybs = {
    u: '/bybs'
    , uList: '/bybs/list'
    , uEdit: '/bybs/edit'
    , uDel: '/bybs/delete'
};

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};
Bybs.isEmpty = function (value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
}

Bybs.dg = function () {
    var grid = new $yd.DataGrid(this.dtable);
    grid.onDblClickRow = function (index, row) {
        Bybs._edit(row['id']);
    };
    grid.onLoadSuccess = function () {
        var rows = Bybs.dtable.datagrid("getRows");
        if(rows.length > 0) {
            Bybs.dtable.datagrid("selectRow", 0);
        }
    };
    grid.onSelect = function (index, row) {
        Bybs.ptable.datagrid("load", {
            id : row.id
        });
    };
    grid.pageSize = 10;
    grid.singleSelect = true;
    grid.rownumbers = true;
    grid.nowarp = false;
    grid.url = Bybs.uList;
    grid.columns = [[
        {field: 'id', checkbox: false, hidden: true}
        , {field: 'code', title: '单号', width: 80}
        , {field: 'order_type', title: '类型', width: 80, formatter: function (value) {
                return value == 0 ? "报溢" : "报损";
            }
        }
        , {
            field: 'order_time', title: '单据日期', width: 80, formatter: function (value) {
                return new Date(value).format('yyyy-MM-dd');
            }
        }
        , {
            field: 'houseName', title: '仓库', width: 120
        }
        , {field: 'num', title: '数量', width: 80}
        , {field: 'fee', title: '总金额', width: 80, formatter: function (value, row, index) {
                return Number(value).toFixed(2);
            }}
        , {
            field: 'status', title: '状态', width: 80, formatter: function (value) {
                return value == 0 ? "待审核" : "已审核";
            }
        }
        , {field: 'cname', title: '创建人', width: 80}
        , {field: 'ctime', title: '创建时间', width: 80}
        , {field: 'otime', title: '审核时间', width: 80}
    ]];
    grid.loadGrid();
};
Bybs.dg2 = function () {
    Bybs.ptable = $('#bybs_table2');
    Bybs.ptable.datagrid({
        url: "/bybsDetail/getDetailList",
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: false,
        columns: [[
            {field: 'goodsName', title: '货品名称', width: 80},
            {field: 'skuName', title: '规格', width: 80},
            {field: 'code', title: '商品编号', width: 80},
            {
                field: 'unit', title: '单位', width: 50, formatter: function (value, row, index) {
                    for (var i = 0; i < Bybs.unitArr.length; i++) {
                        if (value == Bybs.unitArr[i].id) {
                            return Bybs.unitArr[i].text;
                        }
                    }
                    return value;
                }
            },
            {field: 'partsCode', title: '配件编号', width: 80},
            {field: 'price', title: '单价', width: 80, formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }},
            {field: 'num', title: '数量', width: 80},
            {field: 'fee', title: '总额', width: 80, formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }},
            {field: 'houseName', hidden: true},
            {field: 'positionName', hidden: true},
            // {field: 'batch_number', title: '仓库/库位', width: 100, formatter: function (value, row, index) {
            //         if(value.split("_").length == 4) {//入库
            //             var arr = value.split("_");
            //             return "<a style='color:purple'>" + arr[1] + "：" + arr[3] + "</a>";
            //         } else {
            //             var arr = value.split(",");
            //             var result = "";
            //             var first = "";
            //             for (var i = 0; i < arr.length; i++) {
            //                 var arr2 = arr[i].split("_");
            //                 result += arr2[3] + " " + arr2[4] + " X " + arr2[6] + "\n"
            //                 if (first == "") {
            //                     first += arr2[3] + " " + arr2[4] + " X " + arr2[6];
            //                 }
            //             }
            //             return "<a style='color:purple' title='" + result + "'>" + first + (arr.length > 1 ? "..." : "") + "</a>";
            //         }
            //     }}
        ]]
    });
};
Bybs.formatDetail = function (value) {
    if (Bybs.isEmpty(value)) {
        return "";
    }
    var result = "";
    var first = "";
    var arr = value.split(",");
    if (arr.length == 1) {
        return "<a style='color:purple' title='" + value + "'>" + value + "</a>";
    }
    for (var i = 0; i < arr.length; i++) {
        result += arr[i] + "\n";
        if (i == 0) {
            first = result;
        }
    }
    var html = "<a style='color:purple' title='" + result + "'>" + first + "..." + "</a>";

    return html;
};
Bybs.dg.getOne = function () {
    var sels = Bybs.dg.getSels();
    if (sels.length === 1) {
        return sels[0];
    }
    return null;
};
Bybs.dg.getSels = function () {
    return Bybs.dtable.datagrid('getSelections');
};
// 重置
Bybs.reset = function () {
    $("form.search-form").form('clear');
    Bybs.search();
};
Bybs.audit = function () {
    var row = Bybs.dtable.datagrid('getSelected');
    if(!row) {
        $yd.alert("选择记录");
        return;
    }
    if(row.status == 1) {
        $yd.alert("无法重复审核");
        return;
    }
    $yd.confirm("审核后将生成相应的出入库单，确认信息无误？", function () {
        $yd.post("/bybs/audit",{id:row.id}, function (data) {
            if($yd.isEmpty(data.message) || data.message == "操作成功") {
                $yd.alert("操作成功", function () {
                    Bybs.search();
                })
            } else {
                $yd.alert(data.message);
            }
        });
    });
};
// 处理按钮
Bybs.btn = function () {
    var sb = new $yd.SearchBtn($(Bybs.obtn));
    sb.create('remove', '删除(DEL)', Bybs.remove);
    sb.create('edit', '审核(Shift+V)', Bybs.audit);
    sb.create('refresh', '刷新(F2)', Bybs.refresh);
    sb.create('edit', '编辑(Shift+E)', Bybs.edit);
    sb.create('plus', '新建(Shift+N)', Bybs.plus);
};
//删除
Bybs.remove = function () {
    var sel = Bybs.dg.getOne();
    if (!sel) {
        $yd.alert('选中记录');
        return;
    }
    if(sel.status == 1) {
        $yd.alert('已审核无法删除');
        return;
    }
    $yd.confirm(function () {
        $.post(Bybs.uDel, {ids: [sel.id]}, function (data) {
            if($yd.isEmpty(data.message) || data.message == "操作成功") {
                $yd.alert("操作成功", function () {
                    Bybs.search();
                })
            } else {
                $yd.alert(data.message);
            }
        });
    })
};

Bybs.edit = function () {
    var sel = Bybs.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    Bybs._edit(sel['id'])
};
// 表单预处理
Bybs.preForm = function () {
    new $yd.combobox("customerId").load("/customer/select");
};
Bybs._edit = function (id) {
    parent.inv.OpenPage("/bybs/edit?id=" + id, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "                                <span class=\"menu-text\"> 报溢报损单详情 </span>\n" +
        "                                <b class=\"arrow \"></b>", true)
};
//新增
Bybs.plus = function () {
    parent.inv.OpenPage("/bybs/add?orderType=0", "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "                                <span class=\"menu-text\"> 新建报溢报损 </span>\n" +
        "                                <b class=\"arrow \"></b>", true)
};
//
Bybs.refresh = function () {
    window.location.reload();
};
//搜索
Bybs.search = function () {
    Bybs.dtable.datagrid('load', Bybs.sform.serializeObject());
};
Bybs.keyDown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    // console.log("add.js")
};
Bybs.keyUp = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    if (e.keyCode == 46) {//del
        Bybs.remove();
    }
    if (e.keyCode == 113) {//F2
        Bybs.refresh();
    }
    if (e.shiftKey && e.keyCode == 78) {
        Bybs.plus();//生单: Shift + N
    }
    if (e.shiftKey && e.keyCode == 69) {
        Bybs.edit();//生单: Shift + E
    }
    if (e.shiftKey && e.keyCode == 86) {
        Bybs.audit();//生单: Shift + V
    }
};
Bybs.init = function () {
    $.ajax({
        type: "POST",
        url: "/sysDict/materiel_MU",
        dataType: "json",
        success: function (data) {
            Bybs.unitArr = data;
        }
    });
    $("#houseId").combobox({
        prompt:'仓库',
        url: "/wWearhouse/list",
        panelHeight:'auto',
        editable:false,
        valueField:'id',
        textField:'name'
    });

    //快捷键
    document.onkeydown = Bybs.keyDown;
    document.onkeyup = Bybs.keyUp;

    //先获取焦点再失去焦点，否则打开页面后若不点击页面，快捷键无效
    $("#startTime").next().find(".textbox-text").focus()
    $("#startTime").next().find(".textbox-text").blur()
};
$(function () {
    Bybs.sform = $('#bybs_form');
    Bybs.dtable = $('#bybs_table');
    Bybs.obtn = '#bybs_btn';

    Bybs.init();
    Bybs.dg(); // 数据表格
    Bybs.btn(); // 初始化按钮
    $yd.bindEnter(Bybs.search);
    $("#searchButton").click(Bybs.search);

    Bybs.dg2(); // 数据表格
});